// components/upload/upload.js
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    count: {            // 最大上传数量
      type: Number,
      value: 9
    }, 
    url: {              // 上传地址
      type: String,
      value: null
    },
    name: {
      type: String,
      value: 'image'
    },
    showClose: {        // 是否显示关闭按钮
      type: Boolean,
      value: true
    },
    sizeType: {
      type: Array,
      value: ['original', 'compressed']
    },
    sourceType: {
      type: Array,
      value: ['album', 'camera']
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    temp_paths: [],     // 微信返回的图片临时存放路径
  },

  /**
   * 组件的方法列表
   */
  methods: {
    addImage(e) {
      let { temp_paths, count, sizeType, sourceType } = this.data;
      let _this = this;
      if(temp_paths.length >= count) return;
      wx.chooseImage({
        count: count - temp_paths.length,
        sizeType, 
        sourceType,
        success: function(res) {
          let { tempFilePaths } = res;
          _this.updateTemp(tempFilePaths);
        },
      })
    },

    remove(e) {
      let { index } = e.currentTarget.dataset;
      let { temp_paths} = this.data;
      temp_paths.splice(index, 1);
      this.updateTemp(temp_paths);
    },

    /**
     * 更新temp_path
     * @tempFilePaths     新增的图片路径
     */
    updateTemp(tempFilePaths) {
      for(let i=0,len = tempFilePaths.length;i<len;i++) {
        this.upload(tempFilePaths[i]);
      }
    },

    prew(e) {
      let { src } = e.currentTarget.dataset;
      wx.previewImage({
        urls: [src],
      });
    },

    upload(filePath) {
      let { url, name, temp_paths } = this.data;
      let _this = this;
      wx.uploadFile({
        url,name,filePath,
        success(res) {
          if (res.statusCode == 200) {
            temp_paths.push(filePath);
            _this.setData({
              temp_paths
            })
            _this.triggerEvent('tempFilePaths', { temp_paths }, {}); 
          }
        },
        fail(res) {
          console.log(res);
        }
      })
    },
  }
})
